<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-09-11
 * Time: 9:24
 */

namespace app\model;


use app\constant\ActivesConst;
use Exception;
use think\Db;

class AdminActives extends Base
{
    public function sku()
    {
        return $this->hasMany('AdminActiveSku', 'aid')->where(['del' => 0]);
    }

    /**
     * 修改活动
     * @param $aid
     * @param $data
     * @return bool|mixed 成功返回true，失败返回false
     */
    public static function doSave($aid, $data)
    {
        Db::startTrans();
        try {
            $model = parent::get($aid);
            if ($model) {
                //已经创建过的活动不允许更新活动类型
                unset($data['type']);
                $affected = $model->save($data, ['id' => $aid]);
                if ($affected) {
                    //更新前先去更新活动id，避免越权
                    $skus = $data['sku'];
                    $ids = [];
                    foreach ($skus as $sku) {
                        $sku['aid'] = $aid;
                        $id = null;
                        if (isset($sku['id'])) {
                            $id = $sku['id'];
                            //把之前有的sku取出来
                            $skuModel = new AdminActiveSku();
                            $result = $skuModel->save($sku,['id'=>$id]);
                            if (!$result) {
                                throw new Exception('保存套餐失败');
                            }
                        } else {
                            $skuModel = AdminActiveSku::create($sku);
                            if (!$skuModel) {
                                throw new Exception('保存套餐失败');
                            }
                            $id = $skuModel->getData('id');
                        }
                        $ids[] = $id;
                        if ($model->type === ActivesConst::ACTIVE_TYPE_KJ && isset($sku['rule_data'])) {
                            $sku['rule_data']['sku_id'] = $id;
                            $done = AdminKanjiaRule::toSave($sku['rule_data']);
                            if (!$done) {
                                throw new Exception('保存砍价规则失败');
                            }
                        }
                    }
                    //先删除本次已经删除的sku
                    $model = new AdminActiveSku();
                    //把库存标记为删除
                    $model->whereNotIn('id', $ids)->where(['aid' => $aid])->update(['del' => 1]);
                    //保存更新
                    Db::commit();
                    return true;
                }
                return false;
            }
        } catch (Exception $e) {
        }
        Db::rollback();
        return false;
    }

    /**
     * 创建活动
     * @param $data
     * @return bool|mixed 创建成功返回数据，失败返回false
     */
    public static function add($data)
    {
        Db::startTrans();
        try {
            $result = parent::create($data);
            if ($result) {
                $data = $result->getData();
                $skus = $data['sku'];
                foreach ($skus as $sku) {
                    $sku['aid'] = $data['id'];
                    $skuModel = AdminActiveSku::create($sku);
                    if (!$skuModel) {
                        throw new Exception('保存失败');
                    }
                    if ($data['type'] === ActivesConst::ACTIVE_TYPE_KJ && isset($sku['rule_data'])) {
                        $created = AdminKanjiaRule::toSave(['tid' => $data['tid'], 'goods_id' => $data['id'], 'rule' => $sku['rule_data']['rule'],'sku_id'=>$skuModel->getData('id')]);
                        if (!$created) {
                            throw new Exception('保存砍价规则失败');
                        }
                    }
                }
                DB::commit();
                return $data;
            }
        } catch (\Exception $e) {
        }
        Db::rollback();
        return false;

    }

    public static function del($where)
    {
        Db::startTrans();
        try {
            $where['del'] = 1;
            $affected = parent::update($where);
            if ($affected) {
                $done = AdminActiveSku::update(['aid' => $where['id'], 'del' => 1],['aid'=>$where['id']]);
                if ($done) {
                    Db::commit();
                    return true;
                }
            }
        } catch (\Exception $e) {
        }
        Db::rollback();
        return false;
    }
}